<!-- 中转出库列表 -->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => selection = e"
      :cell-class-name="cellClassMethod">

    </ex_super_table_page>
    <taskAssign ref="taskAssign" :title="$tt('label_pick_task_assign')" @afterSubmit="afterSubmitTask" :intoTableOption="[
      { key: 'code', label: 'label_inbound_code', 'min-width': 140, 'show-overflow-tooltip': true, },
      { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 120, 'show-overflow-tooltip': true, },
      {
        type: 'operate', operate: [{
          label: 'title_task_assgin_record', click: (row) => this.$refs.detail_task_record.show({
            title: `${this.$tt('label_inbound_code')}:${row.code}/${this.$tt('label_order_code')}:${row.receivingOrderCode}`,
            urlConfig: {
              url: '/wms-api/inbound/WmsInboundTransitReceivingRpc/selectDetail.json',
              data: { id: row.id }
            },
            urlDataHandle: (res) => {
              return res.data.pickingTaskUserId ? [res.data] : []
            }
          })
        }]
      }
    ]" />
    <detail_task_record ref="detail_task_record" :tableModel="[
      { key: 'code', label: 'label_inbound_code' },
      {
        key: 'pickingTaskUserName', label: 'label_pick_task_user',
        formatter: (r, c, v) => this.$formatNameCode(v, r.pickingTaskUserCode)
      },
    ]" />

    <!-- <detail_transfer ref="detail_transfer" /> -->

    <transfer_quick_checkout ref="transfer_quick_checkout" @submit="submitQuickCheckout" />



    <ex_super_dialog_form ref="formDialogCreateOutboundTotalOrder" :title="$tt('title_create_outbound_total_order')"
      v-bind="dialogBindCreateOutboundTotalOrder">

    </ex_super_dialog_form>

    <print_package_generate ref="print_package_generate" />

    <report_anomaly ref="report_anomaly" :orderTypeList="['INBOUND']" system="WMS" @afterSubmitSuccess="reload()" />
    <pack_box_dialog ref="pack_box_dialog" />

    <pack_dialog ref="pack_dialog" @success="reload()" />
  </div>
</template>
<script>
import print_package_generate from '@/component/print/print_package_generate'
import pack_box_dialog from '../component/pack_box_dialog.vue';

import superTablePageFunction from '@/mixin/super-table-page-function';
// import detail_transfer from './dialog/detail_transfer.vue';
import taskAssign from '@/component/wms/taskAssign.vue';

import report_anomaly from '@/component/dialog/report_anomaly.vue'

import detail_task_record from '@/component/dialog/detail_task_record.vue';


import transfer_quick_checkout from './dialog/transfer_quick_checkout.vue';
import emitOnFunction from '@/mixin/emit-on-function';

import page_table_model_manage from '@/mixin/page_table_model_manage';

import pack_dialog from './dialog/pack_dialog'

export default {
  title: "title_transfer_checkout_list",
  mixins: [superTablePageFunction, emitOnFunction("transfer=>checkout_list"), page_table_model_manage],
  components: {
    taskAssign, detail_task_record, transfer_quick_checkout, pack_box_dialog,
    print_package_generate, pack_dialog, report_anomaly,
  },
  data() {
    return {

      selection: [],




      option: {
        search: {
          default: {},
          model: [
            { label: "label_inbound_code", key: "code", },
            { label: "label_order_code", key: "receivingOrderCode", },
            {
              label: "label_customer", key: "customerId", type: "common_customer_choose"
            },
            {
              label: "label_outbound_status", key: "status", type: 'select', enum: 'OverseasStatusEnum',
              filter: it => !['WAIT_INBOUND', 'WAIT_RECEIVING', 'WAIT_PUTAWAY', 'START_RECEIVING'].some(e => it == e)
            },


            { label: "label_is_upload_track_code", key: "isUploadTrackingNumber", type: 'select', enum: 'YesOrNoEnum', fold: true, },
            { label: "label_track_code", key: "trackingNumber", fold: true, },
            { label: "label_create_time", key: "checkoutDate", type: 'date-picker', fold: true, },
          ],

        },
        actionExtra: [
          {
            label: 'label_quick_checkout', attrs: { type: 'primary' }, auth: "wms_transfer_quick_checkout",
            click: this.clickQuickCheckout,
          },
          {
            label: 'label_pick_task_assign', attrs: { type: 'primary' }, auth: 'wms_transfer_checkout_task_assign',
            click: this.clickTaskAssignment,
          },
          {
            label: 'label_sku_pack_box',
            click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
              if (this.selection.length > 1) return this.$message.error(this.$tt('tip_only_select_single_order'))
              const item = _.head(this.selection)
              if (item.boxIsEmpty != 'Y') {
                return this.$message.error(this.$tt('tip_no_need_packbox'))
              }
              if (item.acceptanceStatus != 'ACCEPTANCE_COMPLETED') {
                return this.$message.error(this.$tt('tip_place_first_acceptance'))
              }
              if (item.packingBoxStatus == 'PACKING_BOX_COMPLETED') {
                return this.$message.error(this.$tt('tip_has_operate_finish'))
              }
              this.$refs.pack_box_dialog.show({ order: item })
            },
          },
          // {
          //   label: 'label_print_pack_mark',
          //   click: () => this.printGenerate(this.selection),
          // },
          {
            label: 'label_multiple_box_packing', attrs: { type: 'primary' }, auth: 'wms_transfer_pack',
            click: () => this.$refs.pack_dialog.show(this.selection)
          },
          // {
          //   label: 'label_print_inbound_code',
          //   click: this.$noFunction,
          // },
          {
            label: 'title_create_outbound_total_order', attrs: { type: 'primary' }, auth: 'wms_transfer_create_outbound_total_order',
            click: this.clickTotalOrder,
          },
          // {
          //   label: 'label_export',
          //   click: this.$noFunction,
          // },
        ],
        table: {
          url: "/wms-api/inbound/WmsInboundTransitCheckoutRpc/selectPage.json",

          model: this.init_table_model(),

        }
        ,

      },
      dialogBindCreateOutboundTotalOrder: {
        customClass: 'dialog_auto',
        submitUrl: '/wms-api/inbound/WmsInboundTransitCheckoutRpc/createTotalOrder.json',
        form: {
          inputClass: "form_input_small ",
          model: [
            {
              key: 'items', label: 'text_has_select_order', formType: 'table', itemClass: "", inputClass: "w_fill",
              'max-height': 350,
              model: [
                { key: 'code', label: 'label_inbound_code', 'min-width': 140, 'show-overflow-tooltip': true, },
                { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 120, 'show-overflow-tooltip': true, },
              ],
            },
            { key: 'destinationWarehouseCode', label: 'label_destination_warehouse', type: 'text', inputClass: "bold ", itemClass: "form_item_default", },
            { key: 'checkoutBoxQty', label: 'label_outbound_total_box_count', type: 'text', inputClass: "bold ", },
            { key: 'checkoutPackagingQty', label: 'label_outbound_total_package_count', type: 'text', inputClass: "bold ", },
            { key: 'supplyName', label: 'label_logistics_supplier', type: 'text', inputClass: "bold ", },
          ],
        }
      },
    };
  },
  methods: {
    option_table_model() {
      return [
        { type: 'selection', clickToggle: true, },
        {
          type: 'expandDesc', 'width': 100,
          expandDesc: {
            column: 4, border: true, direction: 'vertical', labelClassName: 'widthdiv4', labelClassName: 'widthdiv4',
            model: [],
          },
        },
        { key: 'trackingNumber', label: 'label_track_code', 'width': 120, 'show-overflow-tooltip': true, keyShow: 'expandDesc', },
        { key: 'referenceNo', label: 'label_customer_reference_no', 'width': 120, 'show-overflow-tooltip': true, keyShow: 'expandDesc', },
        { key: 'supplyName', label: 'label_logistics_supplier', 'width': 120, 'show-overflow-tooltip': true, keyShow: 'expandDesc', },
        {
          key: 'productName', label: 'label_logistics', 'width': 120, 'show-overflow-tooltip': true,
          keyShow: 'expandDesc', formatter: (r, c, v) => this.$formatNameCode(v, r.productCode)
        },

        { key: 'logisticsStatus', label: 'label_logistics_status', keyShow: 'expandDesc', },
        { key: 'transitWarehouseCode', label: 'label_transit_warehouse', keyShow: 'expandDesc', },
        { key: 'code', label: 'label_inbound_code', 'min-width': 140, 'show-overflow-tooltip': true, },
        { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 120, 'show-overflow-tooltip': true, },

        {
          key: 'customerName', label: 'label_customer_info', 'min-width': 100, 'show-overflow-tooltip': true,
          formatter: (r, c, v) => this.$formatNameCode(v, r.customerCode),
        },
        { key: 'receivingBoxQty', label: 'label_receiving_box_number', 'width': 100, },
        { key: 'receivingSkuQty', label: 'label_receiving_number', 'width': 100, },
        { key: 'destinationWarehouseCode', label: 'label_destination_warehouse', 'width': 120, 'show-overflow-tooltip': true, },
        {
          key: 'status', label: 'label_outbound_status', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "OverseasStatusEnum")
        },

        { key: 'isPackaging', label: 'label_is_pack', 'width': 100, formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum"), },
        { key: 'checkoutPackagingQty', label: 'label_check_pack_count', 'width': 100, },
        {
          type: 'operate', width: 160, operate: [
            {
              type: 'more',
              items: [
                {
                  label: 'label_view_detail',
                  click: (row) => { this.clickDetail(row) }
                },
                // { label: 'label_print_inbound_code', click: this.$noFunction },
                // { label: 'label_download_attachment', click: this.$noFunction },
                {
                  label: 'label_acceptance',
                  auth: '/page/wms/transfer/check',
                  disabled: (row) => ["TRANSIT_OUTBOUND"].includes(row.status),
                  click: (row) => { this.gotoCheck(row) }
                },
                {
                  label: 'label_checkout', auth: '/page/wms/transfer/checkout',
                  disabled: (row) => ["TRANSIT_OUTBOUND"].includes(row.status),
                  click: (row) => this.gotoCheckout(row)
                },
                {
                  label: 'label_checkout_confirm', auth: 'wms_transfer_checkout_confirm',
                  disabled: (row) => ["TRANSIT_OUTBOUND"].includes(row.status),
                  click: (row) => this.checkoutConfirm(row)
                },
                {
                  label: 'label_sku_pack_box',
                  disabled: (row) => !["ACCEPTANCE_COMPLETED"].includes(row.acceptanceStatus) && ["PACKING_BOX_COMPLETED"].includes(row.packingBoxStatus),
                  click: (row) => {
                    const item = row
                    this.$refs.pack_box_dialog.show({ order: item })
                  },
                },

                {
                  label: 'label_sku_pack_box_confirm',
                  disabled: (row) => !["PARTIAL_PACKING_BOX"].includes(row.packingBoxStatus),
                  click: (row) => this.packboxConfirm(row)
                },
                // { label: 'label_upload_track', click: this.$noFunction },
                {
                  label: 'label_report_exception',
                  click: (row) => this.reportAnomaly(row)
                },
              ]
            }
          ]
        }
      ]
    },
    reportAnomaly(row) {
      this['$refs']['report_anomaly'].showNew({
        formDisabled: true,
        onlySetData: true,
        data: {
          customerName: row.customerName,
          customerCode: row.customerCode,
          customerId: row.customerId,
          orderNo: row.code,
          orderType: 'INBOUND',
        },
      })
    },
    cellClassMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'status') {
        if (row.status == 'TRANSIT_WAIT_RECEIVING') {
          return 'color_primary'
        } else if (row.status == 'TRANSIT_WAIT_PICKING') {
          return 'color_primary'
        } else if (row.status == 'TRANSIT_PARTIAL_OUTBOUND') {
          return 'color_warning'
        } else if (row.status == 'TRANSIT_OUTBOUND') {
          return 'color_success'
        }
      }
      return ""
    },
    checkoutConfirm(row) {
      this.$confirm(this.$tt('text_is_sure_checkout_confirm'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/wms-api/inbound/WmsInboundTransitCheckoutDetailRpc/checkoutConfirm.json",
          method: 'post', type: 'json',
          data: { receivingId: row.id },
          success: (res) => {
            this.$message.success(this.$tt('tip_submit_success'))
            this.reload()
          }
        })
      }).catch(() => {
      });
    },
    packboxConfirm(row) {
      this.$confirm(this.$tt('text_is_sure_packbox_confirm'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/packingBoxConfirm.json",
          method: 'post', type: 'json',
          data: { id: row.id },
          success: (res) => {
            this.$message.success(this.$tt('tip_submit_success'))
            this.reload()
          }
        })
      }).catch(() => {
      });
    },
    clickTaskAssignment(e) {
      let _list = this.selection
      if (_list.length <= 0) return this.$message.error(this.$tt("tip_noSelect_checkout_list"))
      if (!this.$loginUser.currentWarehouseId) {
        this.$message.error(this.$tt('tip_please_select_operate_warehouse_first'))
        return
      }
      this.$refs['taskAssign'].show(this.$loginUser.currentWarehouseId, _list)
    },
    afterSubmitTask({ select, list }) {

      this.$ajax({
        url: "/wms-api/inbound/WmsInboundTransitCheckoutRpc/assigningPickingTask.json",
        method: 'post', type: 'json',
        data: {
          ids: list.map(it => it.id),
          pickingUserId: select.userId,
          pickingUserCode: select.userCode,
          pickingUserName: select.userName
        },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
          this.$refs['taskAssign'].hide()
        }
      })
    },
    gotoCheck(row) {
      this.$router.push({ name: '/page/wms/transfer/check', params: { 'receivingCode': row.code } })
    },

    gotoCheckout(row) {
      this.$router.push({ name: '/page/wms/transfer/checkout', params: { 'code': row.code } })
    },


    clickDetail(row) {
      this.$router.push({ name: '/page/wms/transfer/inbound_detail', query: { 'id': row.id } })
      // this.$refs['detail_transfer'].show({ params: { id: row.id }, title: `${this.$tt('label_inbound_code')}:${row.code}` })

    },


    clickQuickCheckout() {
      let _list = this.selection
      if (_list.length <= 0) {
        this.$message.error(this.$tt('tip_please_select_order'))
        return
      }
      if (_list.some(e => e.checkoutStatus == 'CHECKOUT_COMPLETED')) {
        this.$alert(_list.filter(e => e.checkoutStatus == 'CHECKOUT_COMPLETED').map(it => it.code).join(","), this.$tt('tip_part_order_status_error_no_operate'), {
          type: 'warning'
        }).then(() => {
        }).catch(() => {
        });
        return
      }
      this.$refs['transfer_quick_checkout'].show({ tableList: _list })
    },
    submitQuickCheckout(list) {
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundTransitCheckoutRpc/batchCheckout.json",
        method: 'post', type: 'json',
        data: { checkoutList: list },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
          this.transfer_quick_checkout = false
        }
      })
    },
    clickTotalOrder() {
      let _list = this.selection;
      if (_list.length <= 0) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      let item = _.head(_list)
      if (_list.some(it => it.destinationWarehouseId != item.destinationWarehouseId)) {
        return this.$message.error(this.$tt('tip_noCreate_outboundTotalOrder_noSomeToWarehouse'))
      }
      if (_list.some(it => it.supplyId != item.supplyId)) {
        return this.$message.error(this.$tt('tip_noCreate_outboundTotalOrder_noSomeProjuct'))
      }
      this.$refs.formDialogCreateOutboundTotalOrder.show({
        destinationWarehouseId: item.destinationWarehouseId,
        destinationWarehouseCode: item.destinationWarehouseCode,
        destinationWarehouseName: item.destinationWarehouseName,
        items: _.cloneDeep(_list),
        supplyId: item.supplyId,
        supplyName: item.supplyName,
        checkoutBoxQty: _list.reduce((sum, it) => sum + it.receivingBoxQty, 0),
        checkoutPackagingQty: _list.reduce((sum, it) => sum + it.checkoutPackagingQty, 0),
        receivingIds: _list.map(it => it.id),
      }, true,)

    },
    submitTotalOrder() {
      this.$refs['totalOrderForm'].validate((valid) => {
        if (valid) {
          this.$ajax({
            url: "/wms-api/inbound/WmsInboundTransitCheckoutRpc/createTotalOrder.json",
            method: 'post', type: 'json',
            data: this.dialogTotalOrderForm,
            success: (res) => {
              this.$message.success(this.$tt('tip_submit_success'))
              this.reload()
            }
          })
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },
    printGenerate(rows) {
      if (rows.length == 0) return this.$message.error(this.$tt('tip_please_select_order'))
      if (_.uniqBy(rows, it => it.destinationWarehouseId).length > 1) {
        return this.$message.error("目的仓不一致")
      }
      const data = {
        hasDestination: rows.length != 0
      }
      if (rows.length > 0) {
        data.destinationWarehouseId = _.head(rows).destinationWarehouseId
        data.destinationWarehouseName = _.head(rows).destinationWarehouseName
      }
      this.$refs.print_package_generate.show(data)
    },
    generatePackageNo() {
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/generatePackageNo.json",
        method: 'post',
        success: (res) => {

        }
      })
    },
  }
};

</script>
<style></style>
